<?php
/**
 * Author:xsc
 * Time:2023/9/21 9:16
 */

namespace App\Extensions\Common;

use App\Extensions\BaseService;
use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use App\Jobs\ApplylogJob;
use App\Traits\HttpHelper;
use Illuminate\Support\Facades\Log;

class ChainService extends BaseService
{

    use HttpHelper;

    private $url;

    public function __construct()
    {
        $this->url = config('chain.chain_url');
    }

    /**
     * 用户NFT转账
     * @param $from_address
     * @param $to_address
     * @param $token_id
     * @return false|mixed
     * @throws BusinessException
     * Author:xsc
     * Time:2023/9/21 14:03
     */
    public function transferFrom($from_address, $to_address, $token_id)
    {
        $url = '/wallet/transferFrom';

        $params = [
            'fromAddress' => $from_address,
            'toAddress'   => $to_address,
            'tokenId'     => $token_id,
        ];

        $res = $this->request($url, $params);

        if (isset($res['code']) && $res['code'] == '200') {
            return $res['data'];
        }
        return false;
    }

    /**
     * 跬步链
     * @param string $url
     * @param array $data
     * @return mixed
     * @throws BusinessException
     * Author:xsc
     * Time:2023/9/8 20:00
     */
    private function request(string $url, array $data = [])
    {
        $url = $this->url . $url;
        Log::info('[跬步链请求参数]' . json_encode($data, JSON_UNESCAPED_UNICODE));

        try {
            $res = $this->sendFormDataPost($url, $data)->getBody()->getContents();
        } catch (\GuzzleHttp\Exception\GuzzleException $exception) {
            throw new BusinessException(ResponseCode::API_ACCESS_ERROR);
        }

        Log::info('[跬步链返回数据]' . $res);

        // 异步记录请求日志
        $log = [
            'action'      => $url,
            'apply_info'  => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
            'result_info' => $res,
            'create_time' => date('Y-m-d H:i:s'),
            'type'        => '跬步链'
        ];
        dispatch(new ApplylogJob($log));

        if (!$res) {
            throw new BusinessException(ResponseCode::API_ACCESS_ERROR);
        }

        return json_decode($res, true);
    }

}
